import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:get/get.dart' as getx;

import '../../../common/api/x_message_assemble_communicate.dart';
import '../../../common/models/im/index.dart';
import '../../../common/utils/event_bus.dart';
import '../../../common/utils/loading.dart';
import '../../../common/utils/log_util.dart';
import '../../../common/utils/o2_http_client.dart';

/// 文件下载处理类
class ImFileDownloadHelper {
  //私有构造函数
  ImFileDownloadHelper._internal();

  //保存单例
  static final ImFileDownloadHelper _singleton =
      ImFileDownloadHelper._internal();

  //工厂构造函数
  factory ImFileDownloadHelper() => _singleton;

  /// 下载中的消息列表
  final List<IMMessage> downLoadingFileMessageList = [];

  final _event = EventBus();

  bool isDownloading(IMMessage message) {
    return downLoadingFileMessageList.contains(message);
  }

  addDownloadMessage(IMMessage message, String savePath) {
    OLogger.d('开始下载， ${message.id} $savePath');
    startDownloadingNotify(message, 0);
    if (downLoadingFileMessageList.contains(message)) {
      return;
    }
    downLoadingFileMessageList.add(message);
    downloadFile(message, savePath);
  }

  Future<void> downloadFile(IMMessage message, String savePath) async {
    final body = message.toBody();
    if (body == null) {
      Loading.showError('args_error'.tr);
      downLoadingFileMessageList.remove(message);
      startDownloadingNotify(message, 1);
      return;
    }
    final file = File(savePath);
    final downloadUrl =
        MessageCommunicationService.to.getIMMsgDownloadFileUrl(body.fileId!);
    Response response = await O2HttpClient.instance.downloadFile(downloadUrl, savePath, onReceiveProgress: (count, total) {
          if (total > 0 && isDownloading(message)) {
            final progress = (count / total);
            startDownloadingNotify(message, progress);
          }
    });
    OLogger.d('下载返回 ${response.statusCode}');
    if (response.statusCode != 200) {
      Loading.showError('im_chat_error_preview_file_fail'.tr);
      if (file.existsSync()) {
        // 下载失败 删除文件
        file.delete();
      }
    }
    downLoadingFileMessageList.remove(message);
    startDownloadingNotify(message, 1);
    OLogger.d('下载完成 ${message.id}');
  }

  /// 通知进度 [progress] 0-1
  startDownloadingNotify(IMMessage message, double progress) {
    final messageBody = message.toBody();
    if (messageBody == null) {
      return;
    }
    messageBody.fileDownloadProgress = progress;
    message.body = json.encode(messageBody.toJson());
    _event.emit(EventBus.imDownloadFileRefreshMsg, message);
  }
 

  /// 后端上传文件，完成后发送真正的消息 并刷新
  Future<void> uploadImFile(String filePath, String conversationId, IMMessage imMessage, IMMessageBody body) async {
     File file = File(filePath);
      final fileRes = await MessageCommunicationService.to.uploadFileToIM(conversationId, body.type!, file, onSendProgress: (count, total) {
        if (total > 0) {
          final progress = (count / total);
          startDownloadingNotify(imMessage, progress);
        }
      });
      if (fileRes == null) {
        Loading.showError('im_chat_error_upload_fail'.tr);
        return;
      }
      body.fileId = fileRes.id;
      body.fileExtension = fileRes.fileExtension;
      body.fileName = fileRes.fileName;
      body.fileTempPath = null;
      body.fileDownloadProgress = 1; // 结束进度
      imMessage.body = json.encode(body.toJson());
      OLogger.d("消息body2: ${imMessage.body}");
      final id = await MessageCommunicationService.to.sendMessage(imMessage);
      if (id != null && id.id != null) {
          _event.emit(EventBus.imDownloadFileRefreshMsg, imMessage);
      } else {
        OLogger.e('发送消息失败!');
      }
       
  }
  
}
